package com.zhouzhou.fastjava.vfs;

import com.zhouzhou.fastjava.vfs.exception.VFSException;
import org.apache.commons.io.IOUtils;

import java.io.*;


/**
 * @author mojianlan
 * @date Jun 29, 2016
 */

public class LocalDiskVFS extends AbstractVFS {

    private final String rootDir;

    public LocalDiskVFS(String rootDir) {
        if (!new File(rootDir).exists()) {
            throw new VFSException(rootDir + " not exists");
        }
        this.rootDir = rootDir;
    }

    @Override
    protected void storeInternal(InputStream is, String dir, String filename) {

        OutputStream os = null;
        try {
            os = new FileOutputStream(rootDir + dir + filename);
            IOUtils.copy(is, os);
        } catch (Exception e) {
            throw new VFSException("Can't store " + dir + filename, e);
        } finally {
            IOUtils.closeQuietly(os);
            IOUtils.closeQuietly(is);
        }
    }

    @Override
    protected void mkdirs(String dir) {
        String targetDir = rootDir + dir;
        File dirFile = new File(targetDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
    }

    @Override
    public InputStream retrieve(String uri) throws VFSException, FileNotFoundException {

        return new FileInputStream(rootDir + uri);
    }

}